<?php
namespace app\admin\controller\final_accounts;

use app\admin\model\FinalAccountsIndex;
use app\admin\model\FinalAccountsClassify;
use app\admin\model\FinalAccountsType;
use app\admin\service\TriggerService;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use think\App;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\annotation\ControllerAnnotation;
use jianyan\excel\Excel;
use EasyAdmin\upload\Uploadfile;

/**
 * Class Index
 * @package app\admin\controller\final_accounts
 * @ControllerAnnotation(title="决算详情")
 */

class Index extends AdminController
{
    use Curd;
    public $classify;
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new FinalAccountsIndex();
        $this->classify = new FinalAccountsClassify();
    }



    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {

        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();
            $count = $this->model
                ->withJoin(['classify','classifys'], 'LEFT')
                ->where($where)
                ->where('status',1)
                ->count();
            $list = $this->model
                ->withJoin(['classify','classifys'], 'LEFT')
                ->where($where)
                ->where('status',1)
                ->page($page, $limit)
                ->order(['time' => 'desc'])
                ->select();

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

     /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();

            $rule = [
                'classify_id|所属分类'   => 'require',
                'time|日期'   => 'require',
            ];
            $this->validate($post, $rule);
            try {
                $pid = FinalAccountsClassify::where('id',$post['classify_id'])->value('pid');
                if($pid == 0){
                    $post['last_class_id'] = $post['classify_id'];
                }else{
                    $post['last_class_id'] = $pid;
                }
                $post['time'] = strtotime($post['time']);
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }

        $pidMenuList = $this->classify->getPidMenuList();
        array_shift($pidMenuList);
        $this->assign('pidMenuList', $pidMenuList);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model->find($id);

        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'classify_id|所属分类'   => 'require',
                'time|日期'   => 'require',
            ];
            $this->validate($post, $rule);
            try {
                $pid = FinalAccountsClassify::where('id',$post['classify_id'])->value('pid');
                if($pid == 0){
                    $post['last_class_id'] = $post['classify_id'];
                }else{
                    $post['last_class_id'] = $pid;
                }
                $post['time'] = strtotime($post['time']);
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            if ($save) {
                $this->success('保存成功');
            } else {
                $this->error('保存失败');
            }
        }
        $pidMenuList = $this->classify->getPidMenuList();
        array_shift($pidMenuList);
        $row['time'] = date('Y-m-d',$row['time']);
        $this->assign('pidMenuList', $pidMenuList);
        $this->assign('row', $row);
        return $this->fetch();
    }


    /**
     * @NodeAnotation(title="上传")
     */
    public function  uploadFile(){
        set_time_limit(0);
        $data = [
            'upload_type' => 'local',
            'file'        => $this->request->file('file'),
        ];
        $uploadConfig = sysconfig('upload');
        empty($data['upload_type']) && $data['upload_type'] = $uploadConfig['upload_type'];
        try {
            $upload = Uploadfile::instance()
                ->setUploadType($data['upload_type'])
                ->setUploadConfig($uploadConfig)
                ->setFile($data['file'])
                ->save();
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $time_str = explode(' ',$data['file']->getOriginalName());
        $time_str = substr(trim($time_str[0]),0,4).'-'.substr(trim($time_str[0]),4,6);
        if ($upload['save'] == true) {
            $arr = Excel::import_color($upload['name']);
            unset($arr[1]);
            $class_arr = FinalAccountsClassify::field('id,title,pid')->select()->toArray();
            if($class_arr){
                foreach($class_arr as $key => $value){
                    if($value['pid'] == 0){
                        $class_last[] = $value;
                    }else{
                        $class_now[] = $value;
                    }
                }
               $class_name_arr = array_column($class_last,'id','title');
               $class_now_name_arr = array_column($class_now,'id','title');
            }
        
            $type = [
                '当期现金净流入'=> 1,
                '当期支出'=> 2,
                '当期毛利'=> 3,
                '当期毛利率'=> 4,
                '当期负债'=> 5,
            ];
            $last_class_id = 0;
            foreach ($arr as $key => $value){
                if($key < 7){
                    $insert[] = [
                        'classify_id' => $class_arr ? $class_name_arr[$value[0]['data']] ?? 0 : 0,
                        'last_class_id' => $class_arr ? $class_name_arr[$value[0]['data']] ?? 0 : 0,
                        'time'=> strtotime($time_str),
                        'total' => $value[1]['data'] ?? 0,
                        'project_total' => $value[2]['data'] ?? 0,
                        'no_project_total' => $value[3]['data'] ?? 0,
                        'teacher_project_total' => $value[4]['data'] ?? 0,
                        'kb_total' => $value[5]['data'] ?? 0,
                        'kb_project_total' => $value[6]['data'] ?? 0,
                    ];
                }else{
                    if($value[0]['bold']){
                        $last_class_id = $class_name_arr[$value[0]['data']] ?? 0;
                    }
                    
                    if($value[0]['bold'] === false && $value[0]['data'] != '合计'){
                        $insert[] = [
                            'classify_id' => $class_arr ? $class_now_name_arr[$value[0]['data']] ?? 0 : 0,
                            'last_class_id' => $last_class_id,
                            'time'=> strtotime($time_str),
                            'total' => $value[1]['data'] ?? 0,
                            'project_total' => $value[2]['data'] ?? 0,
                            'no_project_total' => $value[3]['data'] ?? 0,
                            'teacher_project_total' => $value[4]['data'] ?? 0,
                            'kb_total' => $value[5]['data'] ?? 0,
                            'kb_project_total' => $value[6]['data'] ?? 0,
                        ];
                    }
                }
            }
            // var_dump($insert);die;
            $types = FinalAccountsIndex::create_data($insert);
            if($types){
                return json(['code'=> 200,'msg' => '上传成功','data' => '']);
            }else{
                return json(['code'=> 500,'msg' => '上传失败','data' => '']);
            }

        } else {
            return json(['code'=> 500,'msg' => $upload['msg'],'data' => '']);
        }
    }


}





































?>